﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IntroduceCompany.Singleton;
using IntroduceCompany.DTO;
using System.ComponentModel.DataAnnotations;
using IntroduceCompany.Util;
using System.Data.Linq;
using System.IO;

namespace IntroduceCompany.Models
{

    public class Language_Validation
    {
        //[System.ComponentModel.DataAnnotations.MetadataType(typeof(IntroduceCompany.Models.Language_Validation))]

        [Required(ErrorMessage = "Mã ngôn ngữ phải có.")]
        [RegularExpression(ConstantClass.testLanguageCode, ErrorMessage = "Mã ngôn ngữ gồm 2 ký tự chữ cái.")]
        public String LanguageID { get; set; }

        [Required(ErrorMessage = "Tên ngôn ngữ phải có.")]
        public String LanguageName { get; set; }

      
        //[Range(1, 20, ErrorMessage = "Vị trí ngôn ngữ phải là số nguyên.")]
        [RegularExpression(ConstantClass.testPositiveInteger, ErrorMessage = "Vị trí ngôn ngữ phải là số nguyên.")]
        [Required(ErrorMessage = "Vị trí ngôn ngữ phải có.")]
        public String LanguageLocation { get; set; }

    }


    public class LanguageModels
    {

        public IQueryable<Language> GetLanguageList_Backend()
        {
            return DataSingleton.GetInstance().Languages.OrderBy(l => l.LanguageLocation).OrderBy(l => l.LanguageLocation); ;
        }

        public IQueryable<Language> GetLanguageList()
        {
            return DataSingleton.GetInstance().Languages.Where(l => l.LanguageVisible == true).OrderBy(l => l.LanguageLocation);
        }


        internal Language GetLanguageDetails(String languageID)
        {
            return DataSingleton.GetInstance().Languages.SingleOrDefault(lang => lang.LanguageID == languageID);
        }

        /// <summary>
        /// Update language visible
        /// </summary>
        /// <param name="languageID"></param>
        /// <param name="languageVisible"></param>
        internal void ChangeLanguageVisible(string languageID, bool languageVisible)
        {
            try
            {
                Language temLanguage = DataSingleton.GetInstance().Languages.SingleOrDefault(lang => lang.LanguageID == languageID);
                temLanguage.LanguageVisible = !languageVisible;
                DataSingleton.GetInstance().Languages.Context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                DataSingleton.GetInstance().Refresh(RefreshMode.OverwriteCurrentValues, DataSingleton.GetInstance());
            }
        }


        /// <summary>
        /// Check LanguageID is existed or not. True is existed
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        internal bool CheckLanguageIDExisted(String languageID)
        {
            return DataSingleton.GetInstance().Languages.Any(lang => lang.LanguageID == languageID);
        }



        /// <summary>
        /// Create Language
        /// </summary>
        /// <param name="language"></param>
        /// <param name="newImageMenu"></param>
        /// <returns></returns>
        internal bool CreateLanguage(Language language, string newImageMenu)
        {
            try
            {
                if (newImageMenu != null && newImageMenu != "")
                {
                    language.FlagImage = newImageMenu;
                }

                DataSingleton.GetInstance().Languages.InsertOnSubmit(language);
                DataSingleton.GetInstance().Languages.Context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                DataSingleton.GetInstance().Refresh(RefreshMode.OverwriteCurrentValues, DataSingleton.GetInstance());
            
                return false;
            }
            return true;
        }


        /// <summary>
        /// Update language
        /// </summary>
        /// <param name="language"></param>
        /// <param name="newImageMenu"></param>
        internal bool EditLanguage(Language language, string newImageMenu)
        {
            try
            {
                if(newImageMenu != null && newImageMenu != ""){
                    language.FlagImage = newImageMenu;
                }
                language.LanguageVisible = true;
                General_dto.ClearCacheDataContext(DataSingleton.GetInstance());
                DataSingleton.GetInstance().Languages.Attach(language, true);
                DataSingleton.GetInstance().Refresh(RefreshMode.KeepCurrentValues, language);
                DataSingleton.GetInstance().Languages.Context.SubmitChanges();

                //Language tempLang = DataSingleton.GetInstance().Languages.SingleOrDefault(lang => lang.LanguageID == language.LanguageID);
                //tempLang.LanguageID = language.LanguageID.ToLower();
                //tempLang.LanguageName = language.LanguageName;
                //tempLang.LanguageLocation = language.LanguageLocation;
                //if (newImageMenu != null && newImageMenu != "")
                //{
                //    tempLang.FlagImage = newImageMenu;
                //}

                //DataSingleton.GetInstance().Languages.Context.SubmitChanges();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                DataSingleton.GetInstance().Refresh(RefreshMode.OverwriteCurrentValues, DataSingleton.GetInstance());
            
                return false;
            }
            return true;

        }


        /// <summary>
        /// Delete Language
        /// </summary>
        /// <param name="languageID"></param>
        internal void DeleteLanguage(string languageID, String fullImagePath)
        {
            try
            {
                Language temLang = DataSingleton.GetInstance().Languages.SingleOrDefault(lang => lang.LanguageID == languageID);

                DataSingleton.GetInstance().Languages.DeleteOnSubmit(temLang);
                DataSingleton.GetInstance().Languages.Context.SubmitChanges();

                //Delete physical language icon
                if (temLang.FlagImage != "")
                {
                    string LocalFile = fullImagePath + temLang.FlagImage;
                    if (File.Exists(LocalFile))
                        File.Delete(LocalFile);
                }

            }
            catch (Exception ex)
            {
                Language temLang = DataSingleton.GetInstance().Languages.SingleOrDefault(lang => lang.LanguageID == languageID);
                DataSingleton.GetInstance().Refresh(RefreshMode.OverwriteCurrentValues, temLang);
                Console.WriteLine(ex.Message);
            }
        }


        /// <summary>
        /// Build seo link url for language chooser user control
        /// </summary>
        /// <param name="current_Url"></param>
        /// <returns></returns>
        internal String BuildCultureChooserUserControl(String current_Url)
        {
            IQueryable<Language> langView = DataSingleton.GetInstance().Languages.Where(l => l.LanguageVisible == true).OrderBy(l => l.LanguageLocation);
            string result = "";
            if (current_Url.Length > 4) // When access by menu or details link
            {
                string[] url_parts = current_Url.Split(new char[] { '/' });

                if (url_parts[2] == "art") // Article List
                {
                    string articleTypeID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetMenuListModels().CheckMenuList_WithLanguage(Convert.ToInt16(articleTypeID), item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;

                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(articleTypeID, item.LanguageID);

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "artDe") // Article Details
                {
                    string articleTypeID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    int articleID = DataSingleton.GetArticleModels().GetArticleIDBy_SEO_URL(url_parts[4]);
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetArticleModels().CheckArticle_WithLanguage(articleID, item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;

                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(articleTypeID, item.LanguageID);
                            url_parts[4] = DataSingleton.GetArticleModels().GetArticle_SEO_URL_By_ArticleID_LanguageID(articleID, item.LanguageID);
                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "npr" || url_parts[2] == "pr" || url_parts[2] == "sur") //Product List
                {
                    string menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetMenuListModels().CheckMenuList_WithLanguage(Convert.ToInt16(menuListID), item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;

                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(menuListID, item.LanguageID);

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "prDe") // Product Details
                {
                    string menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    string productID = DataSingleton.GetProductModels().GetProductIDByProductSeoUrl(url_parts[4]);
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetProductModels().CheckProduct_WithLanguage(productID, item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;

                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(menuListID, item.LanguageID);
                            url_parts[4] = DataSingleton.GetProductModels().GetProductSeoUrl_By_ProductID_LanguageID(productID, item.LanguageID);
                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "alb")
                {
                    string menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    foreach (var item in langView)
                    {
                        url_parts[1] = item.LanguageID;
                        url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(menuListID, item.LanguageID);
                        string newUrl = string.Join("/", url_parts);

                        result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                    }
                }
                else if (url_parts[2] == "albde")
                {
                    int albumID = DataSingleton.GetAlbumModels().GetAlbumID_By_SEO_URL(url_parts[4]);
                    string menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetAlbumModels().CheckAlbum_WithLanguage(albumID, item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;
                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(
                                           menuListID, item.LanguageID);
                            //url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(
                            //               ConstantClass._Frontend_Album_MenuID.ToString(), item.LanguageID);
                            url_parts[4] = DataSingleton.GetAlbumModels().GetAlbumSEO_URL_By_AlbumID_LanguageID(albumID, item.LanguageID);

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "vid")
                {
                    int videoID = 1;
                    // when url like this : http://localhost:1389/vi/vid/video/1/tieng-viet = > url_parts.Length =5, url_parts[4] esixts.
                    if (url_parts.Length > 5)
                    {
                        videoID = DataSingleton.GetVideoModels().GetVideoID_By_Video_SEO_URL(url_parts[5]);
                    }
                    string menuListID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(url_parts[3]).ToString();
                    foreach (var item in langView)
                    {
                        // check if the record has that language
                        if (DataSingleton.GetVideoModels().CheckVideo_WithLanguage(videoID, item.LanguageID))
                        {
                            url_parts[1] = item.LanguageID;
                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(menuListID, item.LanguageID);
                            if (url_parts.Length > 5)
                            {
                                url_parts[5] = DataSingleton.GetVideoModels().GetVideo_SEO_URL_By_VideoID_LanguageID(videoID, item.LanguageID);
                            }
                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                }
                else if (url_parts[2] == "Feedback")
                {
                    foreach (var item in langView)
                    {
                            url_parts[1] = item.LanguageID;

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                    }
                }
                else if (url_parts[2] == "Cart" || url_parts[2] == "Order")
                {
                    foreach (var item in langView)
                    {
                        url_parts[1] = item.LanguageID;
                        string newUrl = string.Join("/", url_parts);

                        result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                    }
                }

                else 
                {
                    if (url_parts[2] == "Survey" && url_parts[3] == "Poll")// case "Survey" page : SurveyPage
                    {
                        foreach (var item in langView)
                        {
                            url_parts[1] = item.LanguageID;
                            url_parts[2] = "sur";
                            url_parts[3] = DataSingleton.GetMenuListModels().GetMenuSEO_URL_By_MenuListID_LanguageID(ConstantClass._Frontend_Survey_MenuID.ToString(),item.LanguageID);

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }
                    if (url_parts[2] == "Survey" && url_parts[3] == "ResultPage")// case "Survey" page : ResultPage
                    {
                        foreach (var item in langView)
                        {
                            url_parts[1] = item.LanguageID;

                            string newUrl = string.Join("/", url_parts);

                            result += "<li><a href=\"" + newUrl + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                        }
                    }

                }
            }
            else if (current_Url.Length == 4 || current_Url.Length == 3) // When Access root link + languageID
            {
                current_Url = current_Url.Substring(3);
                foreach (var item in langView)
                {
                    result += "<li><a href=\"/" + item.LanguageID + current_Url + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                }
            }
            else if (current_Url.Length == 1)  // When Access root link
            {
                foreach (var item in langView)
                {
                    result += "<li><a href=\"" + item.LanguageID + current_Url + "\"><img src=\"../../../Image/Flag/" + item.FlagImage + "\" alt=\"" + item.LanguageName + "\" title=\"" + item.LanguageName + "\"/></a></li>";
                }
            }
            return result;
        }






    }
}